from django.shortcuts import render, reverse
from django.http import HttpResponse
from .. import models
from . import TypesViews


# Create your views here.
# 后台图书商品列表
def index(request):
    # 获取所有的图书商品信息
    data = models.Books.objects.filter()

    # data[0].BookImgs_set.first()

    # 分配数据
    context = {'data': data}
    # 加载模板
    return render(request, 'myadmin/books/index.html', context)


# 后台图书商品添加表单
def add(request):
    types = TypesViews.selectAllTypes()
    context = {'types': types}
    return render(request, 'myadmin/books/add.html', context)


# 后台图书商品执行添加
def insert(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    data.pop('typeid')

    # 获取选择的分类id
    typeid = request.POST.getlist('typeid')
    # 根据分类id获取分类对象
    typeobjs = models.Booktype.objects.filter(id__in=typeid)

    try:
        # 检测当前是否上传了图片
        if not request.FILES.get('pic', None):
            return HttpResponse('<script>alert("请为书籍添加一张封面图");location.href="history.back";</script>')
        # print(data)
        # print(typeobjs)
        # print(request.FILES.get('pic',None))
        # 创建书籍对象,完成添加
        obj = models.Books(**data)
        obj.save()
        # 给书籍和分类设置关系
        obj.typeid.set(typeobjs)
        # 图书 的图片处理
        img_obj = models.BookImgs()
        img_obj.bookid = obj
        img_obj.img_url = request.FILES.get('pic', None)
        img_obj.save()
        url = reverse('myadmin_books_add')
        return HttpResponse(f'<script>alert("图书商品添加成功");location.href="{url}"</script>')
    except:
        url = reverse('myadmin_books_add')
        return HttpResponse(f'<script>alert("图书商品添加失败");location.href="{url}"</script>')


# 后台图书商品删除
def delete(request):
    # return render(request, 'myadmin/books/delete.html')
    pass


# 后台图书商品编辑
def edit(request):
    # return render(request, 'myadmin/books/edit.html')
    pass
